#include "videoplayerwidget.h"
#include <QMessageBox>
#include <QFileInfo>
#include <QDebug>

/**
 * @brief 构造函数
 * @param parent 父控件
 */
VideoPlayerWidget::VideoPlayerWidget(QWidget *parent)
    : QWidget(parent)
    , m_titleBarWidget(nullptr)
    , m_titleLabel(nullptr)
    , m_togglePlaylistButton(nullptr)
    , m_mainContentWidget(nullptr)
    , m_videoAreaWidget(nullptr)
    , m_videoWidget(nullptr)
    , m_playlistPanel(nullptr)
    , m_playlistTitleLabel(nullptr)
    , m_closePlaylistButton(nullptr)
    , m_addFilesButton(nullptr)
    , m_clearPlaylistButton(nullptr)
    , m_playlistWidget(nullptr)
    , m_controlBarWidget(nullptr)
    , m_progressSlider(nullptr)
    , m_previousButton(nullptr)
    , m_playPauseButton(nullptr)
    , m_nextButton(nullptr)
    , m_timeLabel(nullptr)
    , m_volumeButton(nullptr)
    , m_settingsButton(nullptr)
    , m_volumePanel(nullptr)
    , m_volumeSlider(nullptr)
    , m_playerModel(nullptr)
    , m_transcoder(nullptr)
    , m_transcodeDialog(nullptr)
    , m_playlistVisible(false)
    , m_userSeekingSlider(false)
    , m_playlistAnimation(nullptr)
{
    // 创建Model层
    m_playerModel = new VideoPlayerModel(this);
    
    // 创建转码器
    m_transcoder = new VideoTranscoder(this);
    
    // 初始化UI
    setupUI();
    
    // 连接信号槽
    setupConnections();
    
    // 将视频输出连接到QVideoWidget
    m_playerModel->mediaPlayer()->setVideoOutput(m_videoWidget);
    
    // 启动时检查并清理缓存
    checkCacheOnStartup();
}

/**
 * @brief 析构函数
 */
VideoPlayerWidget::~VideoPlayerWidget()
{
}

/**
 * @brief 清理资源（返回主页时调用）
 */
void VideoPlayerWidget::cleanup()
{
    // 停止播放
    if (m_playerModel) {
        m_playerModel->stop();
        qDebug() << "视频播放器：已停止播放";
    }
    
    // 停止正在进行的转码
    if (m_transcoder) {
        m_transcoder->stopTranscode();
    }
    
    // 关闭转码进度对话框
    if (m_transcodeDialog) {
        m_transcodeDialog->close();
        m_transcodeDialog->deleteLater();
        m_transcodeDialog = nullptr;
    }
    
    // 隐藏音量面板
    if (m_volumePanel && m_volumePanel->isVisible()) {
        m_volumePanel->hide();
    }
    
    // 隐藏播放列表（如果展开的话）
    if (m_playlistVisible) {
        hidePlaylistPanel();
    }
    
    qDebug() << "视频播放器：资源清理完成";
}

/**
 * @brief 初始化UI界面
 */
void VideoPlayerWidget::setupUI()
{
    // 设置窗口固定大小 (1024x570，为主窗口状态栏留出30px空间)
    setFixedSize(1024, 570);
    
    // 主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(0, 0, 0, 0);
    mainLayout->setSpacing(0);
    
    // 创建各个区域
    createTitleBar();
    createVideoArea();
    createPlaylistPanel();
    createControlBar();
    createVolumePanel();
    
    // 添加到主布局
    mainLayout->addWidget(m_titleBarWidget);
    mainLayout->addWidget(m_mainContentWidget);
    mainLayout->addWidget(m_controlBarWidget);
    
    setLayout(mainLayout);
}

/**
 * @brief 创建标题栏
 */
void VideoPlayerWidget::createTitleBar()
{
    m_titleBarWidget = new QWidget(this);
    m_titleBarWidget->setFixedHeight(50);
    m_titleBarWidget->setStyleSheet("QWidget { background-color: #34495e; }");
    
    QHBoxLayout *titleLayout = new QHBoxLayout(m_titleBarWidget);
    titleLayout->setContentsMargins(10, 5, 10, 5);
    titleLayout->setSpacing(10);
    
    // 左侧占位（用于让标题居中）
    titleLayout->addStretch();
    
    // 标题标签（居中显示）
    m_titleLabel = new QLabel("视频播放器", m_titleBarWidget);
    m_titleLabel->setAlignment(Qt::AlignCenter);
    m_titleLabel->setStyleSheet("QLabel { color: white; font-size: 16px; font-weight: bold; }");
    titleLayout->addWidget(m_titleLabel);
    
    titleLayout->addStretch();
    
    // 显示/隐藏播放列表按钮
    m_togglePlaylistButton = new QPushButton("列表", m_titleBarWidget);
    m_togglePlaylistButton->setFixedSize(80, 40);
    m_togglePlaylistButton->setStyleSheet(
        "QPushButton { background-color: #3498db; color: white; border: none; "
        "border-radius: 5px; font-size: 12px; font-weight: bold; } "
        "QPushButton:hover { background-color: #2980b9; } "
        "QPushButton:pressed { background-color: #21618c; }"
    );
    titleLayout->addWidget(m_togglePlaylistButton);
}

/**
 * @brief 创建视频显示区
 */
void VideoPlayerWidget::createVideoArea()
{
    m_mainContentWidget = new QWidget(this);
    
    QHBoxLayout *mainHLayout = new QHBoxLayout(m_mainContentWidget);
    mainHLayout->setContentsMargins(0, 0, 0, 0);
    mainHLayout->setSpacing(0);
    
    // 视频区域容器
    m_videoAreaWidget = new QWidget(m_mainContentWidget);
    QVBoxLayout *videoVLayout = new QVBoxLayout(m_videoAreaWidget);
    videoVLayout->setContentsMargins(0, 0, 0, 0);
    videoVLayout->setSpacing(0);
    
    // 视频显示控件 (高度 = 570 - 50(标题栏) - 80(控制栏) = 440)
    m_videoWidget = new QVideoWidget(m_videoAreaWidget);
    m_videoWidget->setMinimumSize(640, 440);
    m_videoWidget->setStyleSheet("QVideoWidget { background-color: black; }");
    
    videoVLayout->addWidget(m_videoWidget);
    mainHLayout->addWidget(m_videoAreaWidget);
    
    // 播放列表面板（初始隐藏）
    // 在createPlaylistPanel()中创建
}

/**
 * @brief 创建播放列表面板
 */
void VideoPlayerWidget::createPlaylistPanel()
{
    m_playlistPanel = new QWidget(m_mainContentWidget);
    m_playlistPanel->setFixedWidth(0); // 初始宽度为0（隐藏）
    m_playlistPanel->setStyleSheet("QWidget { background-color: #ecf0f1; border-left: 2px solid #bdc3c7; }");
    
    QVBoxLayout *playlistLayout = new QVBoxLayout(m_playlistPanel);
    playlistLayout->setContentsMargins(5, 5, 5, 5);
    playlistLayout->setSpacing(5);
    
    // 播放列表头部
    QWidget *headerWidget = new QWidget(m_playlistPanel);
    headerWidget->setFixedHeight(40);
    QHBoxLayout *headerLayout = new QHBoxLayout(headerWidget);
    headerLayout->setContentsMargins(5, 0, 5, 0);
    headerLayout->setSpacing(5);
    
    m_playlistTitleLabel = new QLabel("播放列表", headerWidget);
    m_playlistTitleLabel->setStyleSheet("QLabel { font-size: 12px; font-weight: bold; color: #2c3e50; }");
    headerLayout->addWidget(m_playlistTitleLabel);
    
    headerLayout->addStretch();
    
    m_closePlaylistButton = new QPushButton("X", headerWidget);
    m_closePlaylistButton->setFixedSize(30, 30);
    m_closePlaylistButton->setStyleSheet(
        "QPushButton { background-color: #e74c3c; color: white; border: none; "
        "border-radius: 15px; font-weight: bold; } "
        "QPushButton:hover { background-color: #c0392b; }"
    );
    headerLayout->addWidget(m_closePlaylistButton);
    
    playlistLayout->addWidget(headerWidget);
    
    // 工具栏
    QWidget *toolbarWidget = new QWidget(m_playlistPanel);
    toolbarWidget->setFixedHeight(40);
    QHBoxLayout *toolbarLayout = new QHBoxLayout(toolbarWidget);
    toolbarLayout->setContentsMargins(5, 0, 5, 0);
    toolbarLayout->setSpacing(5);
    
    m_addFilesButton = new QPushButton("添加", toolbarWidget);
    m_addFilesButton->setFixedSize(60, 35);
    m_addFilesButton->setStyleSheet(
        "QPushButton { background-color: #27ae60; color: white; border: none; "
        "border-radius: 3px; } QPushButton:hover { background-color: #229954; }"
    );
    toolbarLayout->addWidget(m_addFilesButton);
    
    m_clearPlaylistButton = new QPushButton("清空", toolbarWidget);
    m_clearPlaylistButton->setFixedSize(60, 35);
    m_clearPlaylistButton->setStyleSheet(
        "QPushButton { background-color: #e67e22; color: white; border: none; "
        "border-radius: 3px; } QPushButton:hover { background-color: #d35400; }"
    );
    toolbarLayout->addWidget(m_clearPlaylistButton);
    
    playlistLayout->addWidget(toolbarWidget);
    
    // 播放列表
    m_playlistWidget = new QListWidget(m_playlistPanel);
    m_playlistWidget->setAlternatingRowColors(true);
    m_playlistWidget->setStyleSheet(
        "QListWidget { background-color: white; border: 1px solid #bdc3c7; } "
        "QListWidget::item { padding: 5px; } "
        "QListWidget::item:selected { background-color: #3498db; color: white; } "
        "QListWidget::item:hover { background-color: #ecf0f1; }"
    );
    playlistLayout->addWidget(m_playlistWidget);
    
    // 将播放列表面板添加到主内容布局
    QHBoxLayout *mainHLayout = qobject_cast<QHBoxLayout*>(m_mainContentWidget->layout());
    if (mainHLayout) {
        mainHLayout->addWidget(m_playlistPanel);
    }
    
    // 创建动画
    m_playlistAnimation = new QPropertyAnimation(m_playlistPanel, "maximumWidth", this);
    m_playlistAnimation->setDuration(300); // 300ms动画时长
}

/**
 * @brief 创建控制栏
 */
void VideoPlayerWidget::createControlBar()
{
    m_controlBarWidget = new QWidget(this);
    m_controlBarWidget->setFixedHeight(80);
    m_controlBarWidget->setStyleSheet("QWidget { background-color: #2c3e50; }");
    
    QVBoxLayout *controlLayout = new QVBoxLayout(m_controlBarWidget);
    controlLayout->setContentsMargins(10, 5, 10, 5);
    controlLayout->setSpacing(5);
    
    // 进度条
    m_progressSlider = new QSlider(Qt::Horizontal, m_controlBarWidget);
    m_progressSlider->setMinimumHeight(20);
    m_progressSlider->setStyleSheet(
        "QSlider::groove:horizontal { border: 1px solid #999999; height: 8px; "
        "background: #34495e; margin: 2px 0; border-radius: 4px; } "
        "QSlider::handle:horizontal { background: #3498db; border: 1px solid #2980b9; "
        "width: 18px; margin: -5px 0; border-radius: 9px; } "
        "QSlider::handle:horizontal:hover { background: #2980b9; }"
    );
    controlLayout->addWidget(m_progressSlider);
    
    // 控制按钮布局
    QHBoxLayout *buttonsLayout = new QHBoxLayout();
    buttonsLayout->setSpacing(10);
    
    // 上一个按钮
    m_previousButton = new QPushButton("上一个", m_controlBarWidget);
    m_previousButton->setFixedSize(70, 40);
    m_previousButton->setStyleSheet(
        "QPushButton { background-color: #95a5a6; color: white; border: none; "
        "border-radius: 5px; font-size: 11px; } "
        "QPushButton:hover { background-color: #7f8c8d; } "
        "QPushButton:pressed { background-color: #636e72; }"
    );
    buttonsLayout->addWidget(m_previousButton);
    
    // 播放/暂停按钮
    m_playPauseButton = new QPushButton("播放", m_controlBarWidget);
    m_playPauseButton->setFixedSize(70, 40);
    m_playPauseButton->setStyleSheet(
        "QPushButton { background-color: #27ae60; color: white; border: none; "
        "border-radius: 5px; font-size: 11px; font-weight: bold; } "
        "QPushButton:hover { background-color: #229954; } "
        "QPushButton:pressed { background-color: #1e8449; }"
    );
    buttonsLayout->addWidget(m_playPauseButton);
    
    // 下一个按钮
    m_nextButton = new QPushButton("下一个", m_controlBarWidget);
    m_nextButton->setFixedSize(70, 40);
    m_nextButton->setStyleSheet(
        "QPushButton { background-color: #95a5a6; color: white; border: none; "
        "border-radius: 5px; font-size: 11px; } "
        "QPushButton:hover { background-color: #7f8c8d; } "
        "QPushButton:pressed { background-color: #636e72; }"
    );
    buttonsLayout->addWidget(m_nextButton);
    
    buttonsLayout->addStretch();
    
    // 时间标签
    m_timeLabel = new QLabel("00:00 / 00:00", m_controlBarWidget);
    m_timeLabel->setMinimumWidth(120);
    m_timeLabel->setAlignment(Qt::AlignCenter);
    m_timeLabel->setStyleSheet("QLabel { color: white; font-size: 11px; }");
    buttonsLayout->addWidget(m_timeLabel);
    
    buttonsLayout->addStretch();
    
    // 音量按钮
    m_volumeButton = new QPushButton("音量", m_controlBarWidget);
    m_volumeButton->setFixedSize(60, 40);
    m_volumeButton->setStyleSheet(
        "QPushButton { background-color: #3498db; color: white; border: none; "
        "border-radius: 5px; font-size: 11px; } "
        "QPushButton:hover { background-color: #2980b9; } "
        "QPushButton:pressed { background-color: #21618c; }"
    );
    buttonsLayout->addWidget(m_volumeButton);
    
    // 设置按钮
    m_settingsButton = new QPushButton("设置", m_controlBarWidget);
    m_settingsButton->setFixedSize(60, 40);
    m_settingsButton->setStyleSheet(
        "QPushButton { background-color: #7f8c8d; color: white; border: none; "
        "border-radius: 5px; font-size: 11px; } "
        "QPushButton:hover { background-color: #636e72; } "
        "QPushButton:pressed { background-color: #535c68; }"
    );
    buttonsLayout->addWidget(m_settingsButton);
    
    controlLayout->addLayout(buttonsLayout);
}

/**
 * @brief 创建音量面板
 */
void VideoPlayerWidget::createVolumePanel()
{
    m_volumePanel = new QWidget(this);
    m_volumePanel->setFixedSize(60, 150);
    m_volumePanel->setStyleSheet("QWidget { background-color: #34495e; border: 2px solid #2c3e50; border-radius: 5px; }");
    m_volumePanel->hide(); // 初始隐藏
    
    QVBoxLayout *volumeLayout = new QVBoxLayout(m_volumePanel);
    volumeLayout->setContentsMargins(10, 10, 10, 10);
    
    m_volumeSlider = new QSlider(Qt::Vertical, m_volumePanel);
    m_volumeSlider->setRange(0, 100);
    m_volumeSlider->setValue(50);
    m_volumeSlider->setStyleSheet(
        "QSlider::groove:vertical { border: 1px solid #999999; width: 8px; "
        "background: #2c3e50; margin: 0 2px; border-radius: 4px; } "
        "QSlider::handle:vertical { background: #3498db; border: 1px solid #2980b9; "
        "height: 18px; margin: 0 -5px; border-radius: 9px; } "
        "QSlider::handle:vertical:hover { background: #2980b9; }"
    );
    volumeLayout->addWidget(m_volumeSlider);
}

/**
 * @brief 初始化信号连接
 */
void VideoPlayerWidget::setupConnections()
{
    // UI事件连接
    connect(m_playPauseButton, &QPushButton::clicked, this, &VideoPlayerWidget::onPlayPauseClicked);
    connect(m_previousButton, &QPushButton::clicked, this, &VideoPlayerWidget::onPreviousClicked);
    connect(m_nextButton, &QPushButton::clicked, this, &VideoPlayerWidget::onNextClicked);
    
    connect(m_progressSlider, &QSlider::sliderMoved, this, &VideoPlayerWidget::onProgressSliderMoved);
    connect(m_progressSlider, &QSlider::sliderPressed, this, &VideoPlayerWidget::onProgressSliderPressed);
    connect(m_progressSlider, &QSlider::sliderReleased, this, &VideoPlayerWidget::onProgressSliderReleased);
    
    connect(m_volumeButton, &QPushButton::clicked, this, &VideoPlayerWidget::onVolumeButtonClicked);
    connect(m_volumeSlider, &QSlider::valueChanged, this, &VideoPlayerWidget::onVolumeSliderChanged);
    connect(m_settingsButton, &QPushButton::clicked, this, &VideoPlayerWidget::onSettingsClicked);
    
    connect(m_togglePlaylistButton, &QPushButton::clicked, this, &VideoPlayerWidget::onTogglePlaylistClicked);
    connect(m_closePlaylistButton, &QPushButton::clicked, this, &VideoPlayerWidget::onClosePlaylistClicked);
    connect(m_addFilesButton, &QPushButton::clicked, this, &VideoPlayerWidget::onAddFilesClicked);
    connect(m_clearPlaylistButton, &QPushButton::clicked, this, &VideoPlayerWidget::onClearPlaylistClicked);
    connect(m_playlistWidget, &QListWidget::itemDoubleClicked, this, &VideoPlayerWidget::onPlaylistItemDoubleClicked);
    
    // Model信号连接
    connect(m_playerModel, &VideoPlayerModel::playStateChanged, this, &VideoPlayerWidget::onPlayStateChanged);
    connect(m_playerModel, &VideoPlayerModel::positionChanged, this, &VideoPlayerWidget::onPositionChanged);
    connect(m_playerModel, &VideoPlayerModel::durationChanged, this, &VideoPlayerWidget::onDurationChanged);
    connect(m_playerModel, &VideoPlayerModel::currentMediaChanged, this, &VideoPlayerWidget::onCurrentMediaChanged);
    connect(m_playerModel, &VideoPlayerModel::playlistChanged, this, &VideoPlayerWidget::onPlaylistChanged);
    connect(m_playerModel, &VideoPlayerModel::errorOccurred, this, &VideoPlayerWidget::onErrorOccurred);
}

// ========== UI事件槽函数实现 ==========

/**
 * @brief 播放/暂停按钮点击
 */
void VideoPlayerWidget::onPlayPauseClicked()
{
    if (m_playerModel->playState() == VideoPlayerModel::Playing) {
        m_playerModel->pause();
    } else {
        m_playerModel->play();
    }
}

/**
 * @brief 上一个按钮点击
 */
void VideoPlayerWidget::onPreviousClicked()
{
    m_playerModel->previous();
}

/**
 * @brief 下一个按钮点击
 */
void VideoPlayerWidget::onNextClicked()
{
    m_playerModel->next();
}

/**
 * @brief 进度条拖动
 */
void VideoPlayerWidget::onProgressSliderMoved(int position)
{
    m_playerModel->seek(position);
}

/**
 * @brief 进度条按下
 */
void VideoPlayerWidget::onProgressSliderPressed()
{
    m_userSeekingSlider = true;
}

/**
 * @brief 进度条释放
 */
void VideoPlayerWidget::onProgressSliderReleased()
{
    m_userSeekingSlider = false;
    m_playerModel->seek(m_progressSlider->value());
}

/**
 * @brief 音量按钮点击
 */
void VideoPlayerWidget::onVolumeButtonClicked()
{
    if (m_volumePanel->isVisible()) {
        m_volumePanel->hide();
    } else {
        // 计算音量面板位置（在音量按钮上方）
        QPoint buttonPos = m_volumeButton->mapToGlobal(QPoint(0, 0));
        QPoint panelPos = mapFromGlobal(buttonPos);
        panelPos.setY(panelPos.y() - m_volumePanel->height() - 5);
        panelPos.setX(panelPos.x() - (m_volumePanel->width() - m_volumeButton->width()) / 2);
        
        m_volumePanel->move(panelPos);
        m_volumePanel->show();
        m_volumePanel->raise();
    }
}

/**
 * @brief 音量滑块变化
 */
void VideoPlayerWidget::onVolumeSliderChanged(int value)
{
    m_playerModel->setVolume(value);
}

/**
 * @brief 设置按钮点击
 */
void VideoPlayerWidget::onSettingsClicked()
{
    // 创建设置对话框
    PlayerSettingsDialog *dialog = new PlayerSettingsDialog(this);
    
    // 设置当前播放模式和播放速度
    dialog->setPlayMode(m_playerModel->playMode());
    dialog->setPlaybackRate(m_playerModel->playbackRate());
    
    // 连接信号
    connect(dialog, &PlayerSettingsDialog::settingsApplied, this, [this](VideoPlayerModel::PlayMode mode, qreal rate) {
        // 应用设置
        m_playerModel->setPlayMode(mode);
        m_playerModel->setPlaybackRate(rate);
        
        qDebug() << "Settings applied - Mode:" << mode << "Rate:" << rate;
    });
    
    // 显示对话框前，添加缓存清理按钮（临时方案）
    // TODO: 未来可以创建独立的缓存管理对话框
    
    // 显示对话框
    dialog->exec();
    
    // 清理对话框
    dialog->deleteLater();
}

/**
 * @brief 显示/隐藏播放列表按钮点击
 */
void VideoPlayerWidget::onTogglePlaylistClicked()
{
    if (m_playlistVisible) {
        hidePlaylistPanel();
    } else {
        showPlaylistPanel();
    }
}

/**
 * @brief 关闭播放列表按钮点击
 */
void VideoPlayerWidget::onClosePlaylistClicked()
{
    hidePlaylistPanel();
}

/**
 * @brief 添加文件按钮点击
 */
void VideoPlayerWidget::onAddFilesClicked()
{
    QStringList files = QFileDialog::getOpenFileNames(
        this,
        "选择视频文件",
        QDir::homePath(),
        "视频文件 (*.mp4 *.avi *.mkv *.flv *.mov *.wmv *.3gp *.webm);;所有文件 (*)"
    );
    
    if (!files.isEmpty()) {
        for (const QString &file : files) {
            processAndAddVideo(file);  // 使用转码处理方法
        }
    }
}

/**
 * @brief 清空播放列表按钮点击
 */
void VideoPlayerWidget::onClearPlaylistClicked()
{
    QMessageBox::StandardButton reply = QMessageBox::question(
        this,
        "确认清空",
        "确定要清空播放列表吗？",
        QMessageBox::Yes | QMessageBox::No
    );
    
    if (reply == QMessageBox::Yes) {
        m_playerModel->clearPlaylist();
    }
}

/**
 * @brief 播放列表项双击
 */
void VideoPlayerWidget::onPlaylistItemDoubleClicked(QListWidgetItem *item)
{
    int index = m_playlistWidget->row(item);
    m_playerModel->setCurrentIndex(index);
    m_playerModel->play();
}

// ========== Model信号响应槽函数实现 ==========

/**
 * @brief 播放状态变化响应
 */
void VideoPlayerWidget::onPlayStateChanged(VideoPlayerModel::PlayState state)
{
    switch (state) {
    case VideoPlayerModel::Playing:
        m_playPauseButton->setText("暂停");
        m_playPauseButton->setStyleSheet(
            "QPushButton { background-color: #e74c3c; color: white; border: none; "
            "border-radius: 5px; font-size: 11px; font-weight: bold; } "
            "QPushButton:hover { background-color: #c0392b; } "
            "QPushButton:pressed { background-color: #a93226; }"
        );
        break;
    case VideoPlayerModel::Paused:
    case VideoPlayerModel::Stopped:
        m_playPauseButton->setText("播放");
        m_playPauseButton->setStyleSheet(
            "QPushButton { background-color: #27ae60; color: white; border: none; "
            "border-radius: 5px; font-size: 11px; font-weight: bold; } "
            "QPushButton:hover { background-color: #229954; } "
            "QPushButton:pressed { background-color: #1e8449; }"
        );
        break;
    }
}

/**
 * @brief 播放进度更新响应
 */
void VideoPlayerWidget::onPositionChanged(qint64 position)
{
    // 仅在用户未拖动进度条时更新
    if (!m_userSeekingSlider) {
        m_progressSlider->setValue(static_cast<int>(position));
    }
    
    // 更新时间标签
    QString currentTime = formatTime(position);
    QString totalTime = formatTime(m_playerModel->duration());
    m_timeLabel->setText(QString("%1 / %2").arg(currentTime, totalTime));
}

/**
 * @brief 视频时长变化响应
 */
void VideoPlayerWidget::onDurationChanged(qint64 duration)
{
    m_progressSlider->setRange(0, static_cast<int>(duration));
    
    // 更新时间标签
    QString totalTime = formatTime(duration);
    m_timeLabel->setText(QString("00:00 / %1").arg(totalTime));
}

/**
 * @brief 当前视频变化响应
 */
void VideoPlayerWidget::onCurrentMediaChanged(int index)
{
    // 更新播放列表选中项
    m_playlistWidget->setCurrentRow(index);
    
    // 更新标题显示当前播放的视频名称
    if (index >= 0 && index < m_playerModel->mediaCount()) {
        QUrl mediaUrl = m_playerModel->mediaUrl(index);
        QString fileName = QFileInfo(mediaUrl.toLocalFile()).fileName();
        m_titleLabel->setText(QString("视频播放器 - %1").arg(fileName));
    } else {
        m_titleLabel->setText("视频播放器");
    }
}

/**
 * @brief 播放列表变化响应
 */
void VideoPlayerWidget::onPlaylistChanged()
{
    updatePlaylistDisplay();
}

/**
 * @brief 错误处理响应
 */
void VideoPlayerWidget::onErrorOccurred(const QString &errorString)
{
    QMessageBox::warning(this, "播放错误", errorString);
}

// ========== 私有方法实现 ==========

/**
 * @brief 格式化时间显示
 */
QString VideoPlayerWidget::formatTime(qint64 milliseconds)
{
    qint64 seconds = milliseconds / 1000;
    qint64 minutes = seconds / 60;
    seconds = seconds % 60;
    
    return QString("%1:%2")
        .arg(minutes, 2, 10, QChar('0'))
        .arg(seconds, 2, 10, QChar('0'));
}

/**
 * @brief 更新播放列表显示
 */
void VideoPlayerWidget::updatePlaylistDisplay()
{
    m_playlistWidget->clear();
    
    for (int i = 0; i < m_playerModel->mediaCount(); ++i) {
        QUrl mediaUrl = m_playerModel->mediaUrl(i);
        QString fileName = QFileInfo(mediaUrl.toLocalFile()).fileName();
        
        // 添加项到列表
        QListWidgetItem *item = new QListWidgetItem(fileName);
        
        // 当前播放项前添加标记
        if (i == m_playerModel->currentIndex()) {
            item->setText(QString("> %1").arg(fileName));
            item->setForeground(QBrush(QColor("#3498db")));
        }
        
        m_playlistWidget->addItem(item);
    }
}

/**
 * @brief 显示播放列表面板
 */
void VideoPlayerWidget::showPlaylistPanel()
{
    m_playlistVisible = true;
    
    // 设置动画
    m_playlistAnimation->setStartValue(0);
    m_playlistAnimation->setEndValue(250); // 播放列表宽度250px
    m_playlistAnimation->start();
}

/**
 * @brief 隐藏播放列表面板
 */
void VideoPlayerWidget::hidePlaylistPanel()
{
    m_playlistVisible = false;
    
    // 设置动画
    m_playlistAnimation->setStartValue(250);
    m_playlistAnimation->setEndValue(0);
    m_playlistAnimation->start();
}

/**
 * @brief 处理视频添加（包含转码检测）
 */
bool VideoPlayerWidget::processAndAddVideo(const QString &filePath)
{
    // 1. 检测视频信息
    VideoInfo info = m_transcoder->detectVideoInfo(filePath);
    
    // 2. 判断是否需要转码
    if (!info.needsTranscode) {
        // 直接添加到播放列表
        qDebug() << "Video format is optimal, adding directly:" << filePath;
        return m_playerModel->addMedia(filePath);
    }
    
    // 3. 需要转码 - 检查缓存中是否已有转码文件
    QString cachedPath = m_transcoder->getCachedVideoPath(filePath);
    if (QFile::exists(cachedPath)) {
        qDebug() << "Using cached transcoded video:" << cachedPath;
        m_videoPathMap[filePath] = cachedPath;
        return m_playerModel->addMedia(cachedPath);
    }
    
    // 4. 显示转码进度对话框
    QFileInfo fileInfo(filePath);
    m_transcodeDialog = new TranscodeProgressDialog(fileInfo.fileName(), this);
    
    // 5. 连接转码器信号
    connect(m_transcoder, &VideoTranscoder::transcodeProgress, 
            m_transcodeDialog, &TranscodeProgressDialog::updateProgress);
    
    connect(m_transcoder, &VideoTranscoder::transcodeFinished,
            this, [this, filePath](bool success, const QString &outputPath) {
        if (m_transcodeDialog) {
            m_transcodeDialog->close();
            m_transcodeDialog->deleteLater();
            m_transcodeDialog = nullptr;
        }
        
        if (success) {
            qDebug() << "Transcode completed successfully:" << outputPath;
            // 记录映射关系
            m_videoPathMap[filePath] = outputPath;
            // 添加转码后的视频
            m_playerModel->addMedia(outputPath);
        } else {
            QMessageBox::warning(this, "转码失败", 
                "视频转码失败，无法添加到播放列表。\n请尝试其他视频文件。");
        }
    });
    
    connect(m_transcoder, &VideoTranscoder::errorOccurred,
            this, [this](const QString &errorMsg) {
        if (m_transcodeDialog) {
            m_transcodeDialog->setStatusText("错误: " + errorMsg);
        }
        QMessageBox::warning(this, "转码错误", errorMsg);
    });
    
    // 连接取消信号
    connect(m_transcodeDialog, &TranscodeProgressDialog::cancelRequested,
            this, [this]() {
        qDebug() << "User cancelled transcode";
        m_transcoder->stopTranscode();
        if (m_transcodeDialog) {
            m_transcodeDialog->deleteLater();
            m_transcodeDialog = nullptr;
        }
    });
    
    // 6. 开始转码
    QString outputPath = cachedPath;
    bool started = m_transcoder->transcodeVideo(filePath, outputPath);
    
    if (!started) {
        delete m_transcodeDialog;
        m_transcodeDialog = nullptr;
        QMessageBox::warning(this, "转码失败", "无法启动视频转码");
        return false;
    }
    
    // 7. 启动进度对话框的计时器
    m_transcodeDialog->startTimer();
    
    // 8. 显示对话框（阻塞）
    m_transcodeDialog->exec();
    
    return true;
}

/**
 * @brief 启动时检查缓存
 */
void VideoPlayerWidget::checkCacheOnStartup()
{
    if (m_transcoder) {
        m_transcoder->checkAndCleanCache();
        
        qint64 cacheSize = m_transcoder->getCacheSize();
        qDebug() << "Video cache size:" << cacheSize / 1024 / 1024 << "MB";
    }
}

